"""依赖包管理API
提供依赖包的安装、卸载、查询等功能
"""
from flask import Flask, Blueprint, request, jsonify
import sys
import os

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

from services.executor.dependency_manager import dependency_manager
from services.shared.logger import get_logger

# 获取日志记录器
logger = get_logger('dependency_api')

# 创建蓝图
dependency_bp = Blueprint('dependency', __name__)


@dependency_bp.route('/dependencies', methods=['GET'])
def list_dependencies():
    """列出已安装的依赖包"""
    try:
        packages = dependency_manager.get_installed_packages()
        
        return jsonify({
            'success': True,
            'data': packages
        })
        
    except Exception as e:
        logger.error(f"获取依赖包列表失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'获取依赖包列表失败: {str(e)}'
        }), 500


@dependency_bp.route('/dependencies/install', methods=['POST'])
def install_dependency():
    """安装依赖包"""
    data = request.get_json()
    
    if not data:
        return jsonify({
            'success': False,
            'error': '无效的请求数据'
        }), 400
    
    package = data.get('package')
    version = data.get('version')
    index_url = data.get('index_url')  # 镜像源URL
    trusted_host = data.get('trusted_host', False)  # 是否信任主机
    
    if not package:
        return jsonify({
            'success': False,
            'error': '缺少包名'
        }), 400
    
    try:
        # 构建包规格
        package_spec = package
        if version:
            package_spec = f"{package}=={version}"
        
        # 安装包
        success, message = dependency_manager.install_package(
            package_spec, 
            index_url=index_url, 
            trusted_host=trusted_host
        )
        
        if success:
            # 获取安装后的包信息
            package_info = dependency_manager.get_package_info(package)
            
            return jsonify({
                'success': True,
                'message': message,
                'data': package_info
            })
        else:
            return jsonify({
                'success': False,
                'error': message
            }), 500
            
    except Exception as e:
        logger.error(f"安装依赖包失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'安装依赖包失败: {str(e)}'
        }), 500


@dependency_bp.route('/dependencies/<package_name>', methods=['DELETE'])
def uninstall_dependency(package_name):
    """卸载依赖包"""
    try:
        success, message = dependency_manager.uninstall_package(package_name)
        
        if success:
            return jsonify({
                'success': True,
                'message': message
            })
        else:
            return jsonify({
                'success': False,
                'error': message
            }), 500
            
    except Exception as e:
        logger.error(f"卸载依赖包失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'卸载依赖包失败: {str(e)}'
        }), 500


@dependency_bp.route('/packages/requirements_txt', methods=['GET'])
def get_requirements_txt():
    """获取requirements.txt文件内容"""
    try:
        content = dependency_manager.generate_requirements_txt()
        
        return jsonify({
            'success': True,
            'data': {
                'content': content,
                'filename': 'requirements.txt'
            }
        })
        
    except Exception as e:
        logger.error(f"生成requirements.txt失败: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'生成requirements.txt失败: {str(e)}'
        }), 500


@dependency_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify({
        'status': 'healthy',
        'service': 'dependency-api'
    })


def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    app.register_blueprint(dependency_bp, url_prefix='/api')
    
    # 启动时任务状态检查 - 已禁用，防止将正常任务标记为失败后又触发新任务
    # def delayed_startup_check():
    #     """延迟执行启动检查"""
    #     import time
    #     time.sleep(5)  # 等待5秒确保服务完全启动
    #     try:
    #         from services.shared.startup_task_checker import run_startup_task_check
    #         logger.info("开始执行启动时任务状态检查...")
    #         run_startup_task_check()
    #         logger.info("启动时任务状态检查完成")
    #     except Exception as e:
    #         logger.error(f"启动时任务状态检查失败: {e}")
    # 
    # # 在后台线程中执行启动检查
    # import threading
    # startup_thread = threading.Thread(target=delayed_startup_check, daemon=True)
    # startup_thread.start()
    
    return app


if __name__ == '__main__':
    app = create_app()
    # 根据环境变量确定端口，默认5002
    port = int(os.environ.get('DEPENDENCY_API_PORT', 5002))
    app.run(host='0.0.0.0', port=port, debug=False)